package com.pay.controller;

import com.pay.common.response.Response;
import com.pay.common.util.ExcelUtils;
import com.pay.common.util.GsonUtils;
import com.pay.common.util.other.Aa;
import com.pay.dao.entity.ViewLog;
import com.pay.dto.domain.ProductionFile;
import com.pay.dto.request.*;
import com.pay.manager.WareHouseManager;
import com.pay.service.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.util.JSONUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@RestController
@RequestMapping(value = "/api")
public class WareHouseController {
    protected final Logger logger = LoggerFactory.getLogger(WareHouseController.class);

    @Autowired
    private WareHouseManager wareHouseManager;


    @PostMapping("sendPic")
    public Response sendPic(@RequestBody @Valid SendPicReqDto sendPicReqDto, BindingResult result, HttpServletRequest request) throws IOException {
        try {
            if (result.hasFieldErrors()) {
                logger.info("验证出错" + result.getFieldError().getDefaultMessage());
                return Response.fail(result.getFieldError().getDefaultMessage());
            }
            return wareHouseManager.sendPic(sendPicReqDto);
        } catch (Exception e) {
            logger.error("推送图片：" + e);
            return Response.fail("网络异常");
        }
    }

    @PostMapping("login")
    public Response login(@RequestBody @Valid LoginReqDto loginReqDto, BindingResult result, HttpServletRequest request) {
        try {
            if (result.hasFieldErrors()) {
                logger.info("验证出错" + result.getFieldError().getDefaultMessage());
                return Response.fail(result.getFieldError().getDefaultMessage());
            }
            return wareHouseManager.login(loginReqDto, request);
        } catch (Exception e) {
            logger.error("用户登入异常：" + e);
            return Response.fail("网络异常");
        }
    }

    /**
     * 导入产品信息
     *
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/importFile")
    public Response importFile(@RequestParam(value = "uploadFile", required = false) MultipartFile file, HttpServletRequest request) throws Exception {
        try {
            String fileName = file.getOriginalFilename();
            if (!"产品信息导入模板.xls".equalsIgnoreCase(fileName)) {
                logger.error("上传文件格式不正确");
                return Response.fail("上传文件格式不正确");
            }
            long size = file.getSize() / (1024 * 1024);
            if (size > 10 * 1024 * 1024) {
                return Response.fail("文件大小应小于10M！");
            }
            List<ProductionFile> list = ExcelUtils.readExcel("", ProductionFile.class, file);
            if (list == null || list.size() <= 0) {
                return Response.fail("上传不能为空");
            }
            return wareHouseManager.importFile(list, request);

        } catch (Exception e) {
            logger.error("导入产品信息：" + e);
            return Response.fail("网络异常");
        }
    }
    /**
     * 导出日志文件
     *
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping("/downLogInfo")
    public Response downLogInfo(@RequestParam String startDate,String endDate) throws Exception {
        try {
            if(StringUtils.isBlank(startDate)){
                return Response.fail("开始时间不能为空");
            }
            if(StringUtils.isBlank(endDate)){
                return Response.fail("结束时间不能为空");
            }
            LogInfoReq logInfoReq = new LogInfoReq();
            logInfoReq.setStartDate(startDate);
            logInfoReq.setEndDate(endDate);
            return wareHouseManager.downLogInfo(logInfoReq);

        } catch (Exception e) {
            logger.error("导出日志信息异常：" + e);
            return Response.fail("网络异常");
        }
    }
    /**
     * 新增
     *
     * @param result
     * @param request
     * @return
     */
    @PostMapping("production/insert")
    public Response insert(@RequestBody @Valid ProductionInsertDto productionInsertDto, BindingResult result, HttpServletRequest request) {
        try {
            if (result.hasFieldErrors()) {
                logger.info("验证出错" + result.getFieldError().getDefaultMessage());
                return Response.fail(result.getFieldError().getDefaultMessage());
            }

            if (StringUtils.isNotBlank(productionInsertDto.getId())) {
                if (!StringUtils.isNumeric(productionInsertDto.getId())) {
                    return Response.fail("主键编号只能是数字");
                }
            }
            return wareHouseManager.insert(productionInsertDto, request);
        } catch (Exception e) {
            logger.error("用户登入异常：" + e);
            return Response.fail("网络异常");
        }
    }

    @PostMapping("production/delete")
    public Response delete(@RequestBody @Valid List<ProductionDeleteReqDto> productionDeleteReqDtoList) {
        try {
            if (productionDeleteReqDtoList == null || productionDeleteReqDtoList.size() <= 0) {
                return Response.fail("删除至少传入一个主键编号！");
            }
            return wareHouseManager.delete(productionDeleteReqDtoList);
        } catch (Exception e) {
            logger.error("用户登入异常：" + e);
            return Response.fail("网络异常");
        }
    }

    @PostMapping("production/query")
    public Response query(@RequestBody @Valid ProductionSelectReqDto productionDeleteReqDtoList) {
        try {
            return wareHouseManager.query(productionDeleteReqDtoList);
        } catch (Exception e) {
            logger.error("用户登入异常：" + e);
            return Response.fail("网络异常");
        }
    }


    @PostMapping("view/log")
    public Response viewLog(@RequestBody ViewLog viewLog) {
        try {
            return wareHouseManager.viewLogquery(viewLog);
        } catch (Exception e) {
            logger.error("扫描的浏览记录：" + e);
            return Response.fail("网络异常");
        }
    }

    public static void main(String[] args) {
//        BigDecimal aa = new BigDecimal(3);
//        BigDecimal bb = new BigDecimal(2);
//        int cc = aa.divide(bb,2,BigDecimal.ROUND_DOWN).intValue();
//        System.out.println(cc);
//        Map map1 = new HashMap();
//        bb(map1);
//        System.out.println("22->"+GsonUtils.toJson(map1));
//        boolean b = StringUtils.startsWith("22222", "24");
//        System.out.println(b);
        Aa aa = new Aa();
        aa.setAa("11");
        List<Aa> aaa= new ArrayList<>();
        aaa.add(aa);
        for (Aa a:aaa){
            a.setBb("22");
        }
        System.out.println(GsonUtils.toJson(aaa));

    }

    public static void  bb(Map map){
        map.put("aa","bb");
        System.out.println("11->"+GsonUtils.toJson(map));
    }
}